<template>
  <div class="order_list_div" style="position: absolute;width: 100%">
    <!--头部-->
    <m-header :hasTitle="true" title="登录" :hasBack="true" :goBack="gobackBtn">
    </m-header>
    <!-- 旧版 -->
    <!-- <header class="aui-bar aui-bar-nav aui-bar-light opacity_title"> -->
      <!-- <router-link :to=""> -->
      <!-- <div class="go-back" @click="$router.go(-1)"> -->
        <!-- <i></i>
        <i></i>
        <i></i>
      </div> -->
      <!-- </router-link> -->
      <!-- <div class="aui-title">登录</div> -->
    <!-- </header> -->
    <!-- <div style="height:3rem;"></div> -->
    <!-- 旧版 -->
    <div class="aui-content top_div">
      <ul class="aui-list aui-form-list aui-margin-b-15">
        <li class="aui-list-item">
          <div class="aui-list-item-inner">
            <div class="aui-list-item-label">账号</div>
            <div class="aui-list-item-input">
              <input type="number" placeholder="请输入手机号码" v-model="phoneNumber">
            </div>
          </div>
        </li>
        <li class="aui-list-item">
          <div class="aui-list-item-inner">
            <div class="aui-list-item-label">密码</div>
            <div class="aui-list-item-input">
              <input type="password" placeholder="请输入密码" v-model="password">
            </div>
          </div>
        </li>
      </ul>
      <router-link to="forget">
        <p class="forgot_password">忘记密码？</p>
      </router-link>
      <div class="aui-content-padded">
        <div class="aui-btn aui-btn-danger aui-btn-block" @click="signIn">登录</div>
        <router-link to="register">
          <div id="register" class="aui-btn aui-btn-danger aui-btn-block aui-btn-outlined">没有账号？立即注册</div>
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapGetters, mapMutations, mapActions} from 'vuex'
  import Header from "../../real-containers/header";
  import {accountLogin, sendSessionId, accessLogin,saveDeviceInfo} from '../../api/wxh/getData.js'
  import MD5 from '../../utils/md5_wxh.js'
  import {showLoading, hideLoading} from '../../utils/loading.js'
  import {Toast} from '../../utils/toast.js'
  import axios from 'axios'

  export default {
    data() {
      return {
        phoneNumber: null,
        password: null,
        goBack: null
      }
    },
    computed: {
      ...mapGetters('wxh', [
        'sessionId',
        'login',
        'userInfo'
      ])
      ,
      ...mapGetters('zwy', [
        'vuexPhoneNumber',
        'vuexPassword',
      ])
      ,
      rightPhoneNumber: function () {
        return /^1\d{10}$/gi.test(this.phoneNumber)
      }
    },
    beforeCreated() {
      
    }
    ,
    created() {
      if (this.$route.query.logOut) {
        this.$router.go(-1);
        return
      }
      this.goBack = this.$route.query.page;
      if(this.vuexPhoneNumber&&this.vuexPassword){
        //注册之后直接登录
        this.phoneNumber = this.vuexPhoneNumber;
        this.password = this.vuexPassword;
        this.signIn();
      }
    }
    ,
    async mounted() {
      await this.getUserInfo();

    }
    ,
    methods: {
      ...mapActions('wxh', [
        'getUserInfo'
      ])
      ,
      ...mapMutations('wxh', [
        "USER_INFO",
				"LOGO_IN",
				"RECORD_SESSIONID",
				"LOGO_OUT",
				"ClEAR_SESSIONID",
				"CLEAR_INFO"
      ])
      ,
      ...mapActions('qxz', ['updateLocation', 'updateScopeOut']),
      ...mapActions('cjy', [
        'synCart',
        'queryCart'
      ]),
      ...mapActions('lyj', [
        'synFoodCart',
        'queryCart'
      ]),
      ...mapMutations('zwy', [
				'setvuexPhoneNumber',
				'setvuexPassword'
      ]),
      ...mapMutations('xxy', ["setarrpopupnum"]),
      gobackBtn(){
        if (this.goBack) {
          this.$router.go(-1);
          return
        }
        //this.$router.push('/main/profile');
        this.$router.push('profile')
      },
      async signIn() {
        if (!this.rightPhoneNumber) {
          Toast({
            message: '手机号码格式不正确',
            duration: 2000,
            type: 'fail'
          });
          return
        } else if (!(/^[\S]{6,}$/.test(this.password))) {
          Toast({
            message: '密码不正确',
            duration: 2000,
            type: 'fail'
          });
          return
        }
        //调象谱cordova;
        //
        let userName = this.phoneNumber;
        let passWord = this.password;
        let that = this;
        let u = navigator.userAgent;

        // if (u.indexOf('iPhone') > -1 && u.indexOf("xiangpu") > -1) {
        //   cordova.exec(function (res) {
        //   let Version = Number(String(res).split('.').join(''));
        //     Version <= 103 ? loginNative() : loginWeb();
        //   }, function (res) {
        //     loginWeb();
        //   }, "CommonPlugin", "getAppVersion", []);

        // } else if (u.indexOf('Android') > -1 && u.indexOf("xiangpu") > -1) {
        //   cordova.exec(function (res) {
        //     let Version = Number(String(res).split('.').join(''));
        //     console.log(Version,'version')
        //     Version <= 124 ? loginNative() : loginWeb();
        //   }, function (res) {
        //     loginWeb();
        //   }, "AppInfo", "getVersion", []);
        // } else if (u.indexOf("xiangpu") === -1) {
        //   loginWeb();
        // }
        loginWeb();
        function loginNative() {
          showLoading();
          cordova.exec(success, fail, "CommonPlugin", "login", [userName, passWord]);

          async function success(response) {
            localStorage.setItem('sessionId', response);
            let request = await accessLogin('eCode=' + api.enterpriseCode);
            if (request.status === 200) {
              hideLoading();
              if (request.data.returnCode == 0) {
                hideLoading();
                Toast({
                  message: request.data.msg,
                  type: 'warn',
                  duration: api.alertTime_1
                })
                that.ClEAR_SESSIONID('sessionId');
                that.LOGO_IN(false);
                that.USER_INFO(null);

              } else if (request.data.returnCode == 1) {
                hideLoading();
                if (!request.data.data[0]) return;
                that.RECORD_SESSIONID(request.data.data[0]);
                that.USER_INFO(request.data.data[1].user);
                that.LOGO_IN(true);
                
                Toast({
                  message: '登录成功！',
                  duration: 2000,
                  type: 'success'
                });
                await that.synCart();
                if (that.goBack) {
                  that.$router.go(-1);
                  return
                }

                that.$router.push('/main/profile');

                //获取deviceId
                // cordova.exec(deviceIdsuccess, deviceIdfail, "CommonPlugin", "getPushInfo", []);
                //
                async function deviceIdsuccess(resp){
                  console.log(resp,'res');
                  let deviceInfo = {
                    "mobile":that.phoneNumber,
                    "deviceId":JSON.parse(resp).deviceNum,
                    "deviceType":JSON.parse(resp).deviceType,
                    "appName":JSON.parse(resp).appName
                  }
                  let result = await saveDeviceInfo(deviceInfo);

                }

                function deviceIdfail(reserror) {
                  console.log(reserror,'reserror')
                };
              }
            } else {
              hideLoading();
              Toast({
                message: request.data.msg || '网络错误！',
                type: 'warn',
                duration: api.alertTime_1
              })
            }
          }

          function fail(error) {
            hideLoading();
            Toast({
              message: error,
              duration: api.alertTime_1,
              type: 'fail'
            });
          };


        }

        async function loginWeb() {
          showLoading();
          let deviceId = 'testDeviceId';
          let deviceType = 'android';
          let appName = 'ningjiaxianshengAndroid';

          if(u.indexOf("xiangpu") > -1){
            //获取deviceId
            cordova.exec(deviceIdsuccess, deviceIdfail, "CommonPlugin", "getPushInfo", []);
          }else{
            loginFun();
          }
          
          async function loginFun() {
            let res = await accountLogin(that.phoneNumber, MD5(that.password), window.api.enterpriseCode,deviceId,deviceType,appName);
            if (res.status === 200) {
              if (res.data.returnCode === 0) {
                //登陆失败；
                hideLoading();
                Toast({
                  message: res.data.msg,
                  duration: 2000,
                  type: 'fail'
                });
                return
              }
              if (res.data.returnCode === 1) {
                //首页弹框相关
                hideLoading();
                Toast({
                  message: '登录成功！',
                  duration: 2000,
                  type: 'success'
                });
                that.RECORD_SESSIONID(res.data.data[0].sessionId);
                that.USER_INFO(res.data.data[0].user);
                that.LOGO_IN(true);

                if (!res.data.data[0].user.erpVipId) {
                  localStorage.setItem('erpVipId', 1);
                }
                console.log(that.goBack,'66666')
                if(that.goBack == 'cartForFood') {
                  console.log(1)
                  await that.synFoodCart();
                } else {
                  console.log(2)
                  await that.synCart();
                }
                

                if (that.goBack) {
                  that.$router.go(-1);
                }else{
                  that.$router.push({path: 'profile'});
                }

                if(u.indexOf("xiangpu") > -1){
                  //
                  cordova.exec(success2, fail2, "CommonPlugin", "monitorLoginStatus", []);
                }
                function success2(res){
                  that.ClEAR_SESSIONID('sessionId');
                  that.LOGO_OUT(false);
                  that.CLEAR_INFO(null);
                  that.updateLocation(null);
                  that.updateScopeOut(null);
                  localStorage.setItem('chooseAddressActiveIndex', null);
                  localStorage.setItem('locateIn', null);
                  localStorage.setItem('locateOut', null);
                  localStorage.setItem('cartArray', '');
                  localStorage.setItem('cartFoodArray', '');
                  localStorage.removeItem('sessionId', '');
                  that.$store.dispatch('cjy/queryCart');
                  that.setvuexPhoneNumber(null);
                  that.setvuexPassword(null);
                  that.setarrpopupnum([])
                  localStorage.setItem("phoneNumber", "");
                  Toast({
                    message:'您的帐号已在其他设备登录！',
                    type:'warn',
                    duration: 3000
                  })
                  that.$router.push({path: 'login'});							  
                }

                function fail2(res){ 
                  console.log(res,'resfail')
                }
                
              }
            } else {
              Toast({
                message: "网络错误",
                duration: 2000,
                type: 'fail'
              });
              hideLoading();
            }
          }
              
          //
          async function deviceIdsuccess(resp){
            // console.log(JSON.parse(resp),'resp');
            deviceId = JSON.parse(resp).deviceNum;
            deviceType = JSON.parse(resp).deviceType;
            appName = JSON.parse(resp).appName;
            let deviceInfo = {
              "mobile":that.phoneNumber,
              "deviceId":JSON.parse(resp).deviceNum,
              "deviceType":JSON.parse(resp).deviceType,
              "appName":JSON.parse(resp).appName
            }
            loginFun();
            // let result = await saveDeviceInfo(deviceInfo);
                
          }

          function deviceIdfail(reserror) {
            hideLoading();
            Toast({
                message: "cordova请求错误",
                duration: 2000,
                type: 'fail'
              });
          };

        }
      }
    }
    ,
    components: {
      "m-header": Header,
    },
  }
  //
</script>
